//
//  WWPictureCollectionViewController.swift
//  SinWEiBo
//
//  Created by 胡良志 on 2018/5/3.
//  Copyright © 2018年 HuLiangZhi. All rights reserved.
//

import UIKit
let collID = "collID"
let ViewCount : CGFloat = 3 //个数
let ViewMargin : CGFloat = 4 //间距
let ViewCellWidth = (ScreenWidth - (ViewCount + 1) * ViewMargin) / ViewCount
fileprivate let maxCount = 3
class WWPictureCollectionViewController: UIViewController,UICollectionViewDataSource {

    //定义图片数组
    lazy var ArrayImages : [UIImage] = [UIImage]()
    lazy var ArrayIma : [UIImage] = [UIImage()]
    //
    lazy var collectionView: UICollectionView = {
        let Layout = UICollectionViewFlowLayout()
        Layout.itemSize = CGSize(width: ViewCellWidth, height: ViewCellWidth)
        Layout.minimumLineSpacing = ViewMargin
        Layout.minimumInteritemSpacing = ViewMargin
        Layout.sectionInset = UIEdgeInsetsMake(ViewMargin, ViewMargin, 0, ViewMargin)
        let clo = UICollectionView(frame: self.view.bounds, collectionViewLayout: Layout)
        return clo
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(collectionView)
        collectionView.backgroundColor = UIColor.white
        collectionView.dataSource = self
        collectionView.register(WWPictureCollectionViewCell.self, forCellWithReuseIdentifier:collID )
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //如果达到上线,就隐藏掉最后一个
       let Pcount = self.ArrayImages.count == maxCount ? 0 : 1
        return  self.ArrayImages.count + Pcount
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collID, for: indexPath) as! WWPictureCollectionViewCell
        cell.delegate = self
        cell.backgroundColor = UIColor.yellow
        //如果是最后一条数据就特殊处理
        if indexPath.item == self.ArrayImages.count {
            cell.image = nil //给最后一个cell赋值
        }else{
            cell.image = self.ArrayImages[indexPath.item]
        }
    
        return cell
    }
    
}

//MARK: 协议的代理方法
extension WWPictureCollectionViewController : PictureSelectorCellDelegate{
    //添加
    func UserWillAdd(cell: WWPictureCollectionViewCell?) {
        print("增加")
        //图片选择器
        let picker = UIImagePickerController()
        picker.delegate = self
        self.present(picker, animated: true, completion: nil)
    }
    //删除
    func UserWillRemove(cell: WWPictureCollectionViewCell) {
        print("删除")
        //0.根据被点击的cell 通过collectionView 获取对应的indexPath
        guard let indexPath = collectionView.indexPath(for: cell) else {return}
        //在数组删除对应的图片
        self.ArrayImages.remove(at: indexPath.item)
        self.collectionView.reloadData()
        
    }
    
    
}

//MARK: 图片选择器的代理方法
extension WWPictureCollectionViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //实现协议方法  一旦实现该方法, 程序员需要手动dismiss
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//        print(info[UIImagePickerControllerOriginalImage])
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
       self.ArrayImages.append(image)
        
        self.dismiss(animated: true) {
            
        }
        //刷新界面
        self.collectionView.reloadData()
    }
}

/**********************************-----UICollectionViewCell-----*********************************************/


@objc protocol PictureSelectorCellDelegate : NSObjectProtocol {
    //添加图片的协议方法
    @objc optional func UserWillAdd(cell:WWPictureCollectionViewCell?)
    //删除图片的协议方法
    @objc optional func UserWillRemove(cell:WWPictureCollectionViewCell)
}


class WWPictureCollectionViewCell: UICollectionViewCell {
    //定义代理属性
    weak var delegate : PictureSelectorCellDelegate?
    //cell的图片数据
    var image : UIImage?{
        didSet{
            //给cell的图片赋值
            addButton.setImage(image, for: .normal)
            //如果图片有值就隐藏掉删除按钮
            RemoveButton.isHidden = image == nil
        }
    }
    
    override init(frame: CGRect) {
        super .init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI (){
        
        self.contentView.addSubview(addButton)
        self.contentView.addSubview(RemoveButton)
        addButton.snp.makeConstraints { (make) in
            make.edges.equalTo(self.contentView)
        }
        RemoveButton.snp.makeConstraints { (make) in
            make.right.top.equalTo(self.contentView)
        }
        addButton.addTarget(self, action: #selector(addBtnDidCilck), for: .touchUpInside)
        RemoveButton.addTarget(self, action: #selector(RemoveDidClick), for: .touchUpInside)
    }
    
    //增加的点击方法
    @objc private func addBtnDidCilck(){
        //有图片的按钮不能再点击添加
        if image != nil {
            return
        }
        self.delegate?.UserWillAdd!(cell: self)
    }
    //删除的点击方法
    @objc private func RemoveDidClick(){
        
        self.delegate?.UserWillRemove!(cell: self)
    }
    
    

    //MARK: 增加和删除按钮
    //增加按钮
    lazy var addButton: UIButton = {
        let btn = UIButton()
        btn.imageView?.contentMode = .scaleAspectFill
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add_highlighted"), for: .normal)
        return btn
    }()
    //删除按钮
    lazy var RemoveButton: UIButton = {
        let btn = UIButton()
        btn.setImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        return btn
    }()
    
    
}
























